import axios from 'axios'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

export const request = createInctance()
export const userRequest = createUserInctance()

function createInctance () {
  const instance = axios.create({
    // baseURL: 'http://47.113.122.121:8080', // 这里要改成你后端的地址
    baseURL: '/admin',
    timeout: 5000
  })

  instance.interceptors.request.use(handerRequest)
  instance.interceptors.response.use(handerResponse)

  return instance
}

function createUserInctance () {
  const instance = axios.create({
    // baseURL: 'http://47.113.122.121:8080', // 这里要改成你后端的地址
    baseURL: '/user',
    timeout: 5000
  })

  instance.interceptors.request.use(handerRequest)
  instance.interceptors.response.use(handerResponse)

  return instance
}

function handerRequest (config) {
  NProgress.start()
  config.headers.token = `${JSON.parse(sessionStorage.getItem('token'))}`
  return config
}

function handerResponse (response) {
  if (response.status != 200) {
    throw new Error('网络异常')
  }
  NProgress.done()
  // console.log(response.data);
  return response.data
}
